package com.com.cgq.data.exchenge;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cgq on 2015/11/8.
 */
public class ListData {

//    private  Context mContext;
//    private  ListView mListView

    public ListData(/*Context mContext, ListView mListView*/) {
//        this.mContext = mContext;
//        this.mListView = mListView;
    }

    //获取json
    public List<ListDataMember> getJsonData(String url){//第二步getJsonData将url转化为所需要的json对像
        List<ListDataMember> Datamenber_List=new ArrayList<ListDataMember>();
        String jsonString;
        try {
            jsonString = readStream(new java.net.URL(url).openStream());
            JSONObject jsonObject;
            ListDataMember listDataMember;
            jsonObject=new JSONObject(jsonString);
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject=jsonArray.getJSONObject(i);//jsonArray中每一个都是jsonObject
                listDataMember=new ListDataMember();//listDataMember
                listDataMember.strFoodPic=jsonObject.getString("picSmall");
                listDataMember.StrFoodName=jsonObject.getString("name");
                listDataMember.strFoodScore=jsonObject.getString("description");
                Datamenber_List.add(listDataMember);
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Datamenber_List;
    }
    //读取json的字符流
    public String readStream(InputStream in){//传进来一个字节流
        InputStreamReader inReader;
        String result="";
        try {
            String line="";
            inReader=new InputStreamReader(in,"utf-8");//通过InputStreamReader将字节流转化成字符流
            BufferedReader bf=new BufferedReader(inReader);//通过BufferedReader将字符流再读取出来
            while ((line=bf.readLine())!=null) {
                result+=line;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;

    }

}
